package com.yz.fanrenmianshi.job.cycle;

import cn.hutool.core.collection.CollUtil;
import com.yz.fanrenmianshi.annotation.DistributedLock;
import com.yz.fanrenmianshi.esdao.QuestionEsDao;
import com.yz.fanrenmianshi.mapper.QuestionMapper;
import com.yz.fanrenmianshi.model.dto.question.QuestionEsDTO;
import com.yz.fanrenmianshi.model.entity.Question;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 增量同步题目到 es
 */
// todo 取消注释开启任务
@Component
@Slf4j
public class IncSyncQuestionToEs {

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private QuestionEsDao questionEsDao;

    /**
     * 每分钟执行一次
     */
    @Scheduled(fixedRate = 60 * 1000)
    public void run() {
        // 查询近 5 分钟内的数据
        long FIVE_MINUTES = 5 * 60 * 1000L;
        Date fiveMinutesAgoDate = new Date(new Date().getTime() - FIVE_MINUTES);
        List<Question> questionList = questionMapper.listQuestionWithDelete(fiveMinutesAgoDate);
        if (CollUtil.isEmpty(questionList)) {
            log.info("no inc question");
            return;
        }
        // 分离未删除和已删除的题目
        List<Question> activeQuestions = questionList.stream()
                .filter(question -> question.getIsDelete() == 0)
                .collect(Collectors.toList());
        List<Question> deletedQuestions = questionList.stream()
                .filter(question -> question.getIsDelete() == 1)
                .collect(Collectors.toList());
        
        // 同步未删除的题目到ES
        if (CollUtil.isNotEmpty(activeQuestions)) {
            List<QuestionEsDTO> questionEsDTOList = activeQuestions.stream()
                    .map(QuestionEsDTO::objToDto)
                    .collect(Collectors.toList());
            final int pageSize = 500;
            int total = questionEsDTOList.size();
            log.info("IncSyncQuestionToEs start, active questions total {}", total);
            for (int i = 0; i < total; i += pageSize) {
                int end = Math.min(i + pageSize, total);
                log.info("sync active questions from {} to {}", i, end);
                questionEsDao.saveAll(questionEsDTOList.subList(i, end));
            }
            log.info("IncSyncQuestionToEs active questions end, total {}", total);
        }
        
        // 从ES中删除已删除的题目
        if (CollUtil.isNotEmpty(deletedQuestions)) {
            log.info("Deleting {} questions from ES", deletedQuestions.size());
            for (Question deletedQuestion : deletedQuestions) {
                try {
                    questionEsDao.deleteById(deletedQuestion.getId());
                    log.info("Deleted question {} from ES", deletedQuestion.getId());
                } catch (Exception e) {
                    log.error("Failed to delete question {} from ES: {}", deletedQuestion.getId(), e.getMessage());
                }
            }
        }
    }
}